<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas
      id="canvas"
      width="1707px"
      height="800px"
      style="border: solid 1px black"
    >
    </canvas>
    <button class="clear">擦板</button>
    <button class="pen">画笔</button>
  </body>
  <script>
    // 神笔马良
    window.onload = function () {
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      ctx.lineWidth = 20;
      ctx.strokeStyle = "pink";
      var pen = document.querySelector(".pen");
      var dur = false;
      pen.addEventListener("click", function () {
        // 鼠标按下绘图
        canvas.onmousedown = (e) => {
          dur = true;
          ctx.beginPath();
          ctx.moveto(e.clientX, e.clientY);
        };
        // 鼠标抬起停止
        canvas.onmouseup = () => {
          dur = false;
        };
        // 鼠标移入绘图
        canvas.onmousemove = (e) => {
          if (dur) {
            ctx.lineTo(e.clientX, e.clientY);
            ctx.stroke();
          }
        };
      });
      var clear = document.querySelector(".clear");
      clear.addEventListener("click", function (e) {
        // 鼠标按下绘图
        canvas.onmousedown = (e) => {
          dur = true;
          ctx.beginPath();
          ctx.moveto(e.clientX, e.clientY);
        };
        canvas.onmouseup = () => {
          dur = false;
        };
        canvas.onmousemove = (e) => {
          if (dur) {
            ctx.clearRect(e.clientX, e.clientY, 20, 20);
            ctx.stroke();
          }
        };
      });
    };

    
  </script>
</html>
